package com.markul.android.logic.room

import androidx.lifecycle.LiveData
import androidx.room.*
import com.markul.android.logic.model.room.*

@Dao
interface AppDao {
    @Insert
    fun addUser(user: User)

    @Insert
    fun addAlbum(album: Album)

    @Insert
    fun addPhoto(photo: Photo)

    @Query("select * from User where userId=:userId")
    fun getUser(userId: Int): User

    @Query("delete from Album where albumId=:albumId")
    fun deleteAlbum(albumId:Int)

    @Query("delete from Photo where photoOwnerId=:albumId")
    fun deletePhotos(albumId:Int)

    @Transaction
    @Query("select*from Album where albumOwnerId=:albumOwnerId order by albumTime desc,albumId asc")
    fun getAlbumWithPhotos(albumOwnerId: Int): LiveData<List<AlbumWithPhotos>>

    @Transaction
    @Query("select * from Album where albumOwnerId=:userId order by albumTime desc,albumId asc")
    fun getOwnerWithAlbums(userId: Int): LiveData<List<Album>>

    @Transaction
    @Query("select * from Album where albumOwnerId=:userId order by albumId desc")
    fun getAlbums(userId: Int): LiveData<List<Album>>
}

@Dao
interface PublicDao {
    @Insert
    fun addPublicRoom(publicRoom: PublicRoom)

    @Insert
    fun addPublicAlbum(publicAlbum: PublicAlbum)

    @Insert
    fun addPublicPhoto(publicPhoto: PublicPhoto)

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun addUserAndPublicRoomCrossRef(userAndPublicAlbumCrossRef: UserAndPublicRoomCrossRef)

    @SuppressWarnings(RoomWarnings.CURSOR_MISMATCH)
    @Transaction
    @Query(
        "select * " +
                "from UserAndPublicRoomCrossRef " +
                "left join PublicRoom " +
                "on PublicRoom.pRoomId=UserAndPublicRoomCrossRef.pRoomId " +
                "where PublicRoom.pRoomId=:pRoomId"
    )
    fun getPublicRoomWithUsers(pRoomId: Int): LiveData<List<UserAndPublicRoomCrossRef>>

    @SuppressWarnings(RoomWarnings.CURSOR_MISMATCH)
    @Transaction
    @Query(
        "select * " +
                "from UserAndPublicRoomCrossRef " +
                "left join User " +
                "on User.userId=UserAndPublicRoomCrossRef.userId " +
                "where User.userId=:userId"
    )
    fun getUserWithPublicRooms(userId: Int): LiveData<List<UserAndPublicRoomCrossRef>>

    @Query("SELECT*from PublicAlbum where pAlbumOwnerId=:pRoomId")
    fun getPublicRoomWithPublicAlbums(pRoomId: Int): LiveData<List<PublicAlbum>>

    @Transaction
    @Query("SELECT*from PublicAlbum where pAlbumId=:pAlbumId")
    fun getPublicAlbumWithPublicPhotos(pAlbumId: Int): LiveData<PublicAlbumWithPublicPhotos>

}

